package com.example.ui;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.ejlchina.okhttps.HTTP;
import com.ejlchina.okhttps.HttpCall;
import com.ejlchina.okhttps.OkHttps;
import com.ejlchina.okhttps.OnCallback;
import com.example.R;
import com.example.data.Token;
import com.example.kits.Main;
import com.example.okhttps.Tags;
import com.example.okhttps.Urls;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

public class LoginActivity extends AppCompatActivity {



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        EditText username = findViewById(R.id.username);
        EditText password = findViewById(R.id.password);
        findViewById(R.id.login)
            .setOnClickListener(v -> login(username.getText().toString(), password.getText().toString()));

//        AtomicInteger count = new AtomicInteger();

//        Main.repeat(() -> {
//            Log.i("Main Repeat", "执行 REPEAT");
//            return count.incrementAndGet() <= 10;
//        }, 1000);

    }

    private void login(String username, String password) {
        HttpCall post = OkHttps.async(Urls.SIGN_IN)
                .bind(this)
                .tag(Tags.LOADING)
                .addBodyPara("username", username+";" )
                .addBodyPara("password", password)
                .setOnResBean(Token.class, token -> {
                    Log.e("logcat","setOnResBean="+token.toString());
                    if (token.saveToSp(this)) {
                        Toast.makeText(this, "登陆成功", Toast.LENGTH_LONG).show();
                        //startActivity(new Intent(this, MainActivity.class));
                       // finish();
                    } else {
                        Toast.makeText(this, "令牌保存失败！", Toast.LENGTH_LONG).show();
                    }
                })
                .setOnResString(data -> Log.e("logcat", "setOnResString=" + data))
                .setOnException(new OnCallback<IOException>() {
                    @Override
                    public void on(IOException data) {
                        Log.e("logcat", "IOException=" + data.toString());
                    }
                })
                .post();
    }

}
